//
//  DealThings.m
//  OASystem
//
//  Created by mac on 14-5-7.
//  Copyright (c) 2014年 mac. All rights reserved.
//

#import "DealThings.h"

@interface DealThings ()

@end

@implementation DealThings
@synthesize titleStr;
@synthesize workItemGuidStr,operationGuidStr,transitionGuidStr;
@synthesize dealThingsDic;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        
        if(!dealThingsDic)
            dealThingsDic = [[NSDictionary alloc] init];
    }
    return self;
}

//触摸非编辑区域释放键盘
- (void)dismisskeyBoard
{
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
}

//返回上一级
- (void)back
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)initNavi
{
    //初始化UINavigation
    self.navigationItem.titleView = [[UIView alloc] initWithFrame:CGRectMake(110, 0, 100, 44)];
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 44)];
    titleLabel.text = @"待办事宜";
    titleLabel.font = HEIGHT_FONT(18.0f);
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.textColor = [UIColor whiteColor];
    [self.navigationItem.titleView addSubview:titleLabel];
    
    //添加导航又边用户信息
    //初始化UINavigation左按钮
    UIButton *helloButton = [[UIButton alloc] initWithFrame:CGRectMake(5, 10, 80, 24)];
    [helloButton setTitle:[NSString stringWithFormat:@"你好，%@",USER_NICK_NAME] forState:UIControlStateNormal];
    helloButton.titleLabel.font = HEIGHT_FONT(13.0f);
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:helloButton];
    
    //初始化UINavigation左按钮
    UIButton *naviButton = [[UIButton alloc] initWithFrame:CGRectMake(5, 10, 45, 24)];
    [naviButton setTitle:@"返回" forState:UIControlStateNormal];
    naviButton.titleLabel.font = HEIGHT_FONT(13.0f);
    [naviButton setBackgroundImage:[UIImage imageNamed:@"title_back_bg_n.png"] forState:UIControlStateNormal];
    [naviButton setBackgroundImage:[UIImage imageNamed:@"title_back_bg_p.png"] forState:UIControlStateHighlighted];
    [naviButton addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:naviButton];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.view.backgroundColor = NOTICEBOARD_BACKCOLOR;
    [self initNavi];
    
    if(!allTipArr)
    {
        allTipArr = [[NSArray alloc] init];
        if([[dealThingsDic objectForKey:@"commOpinion"] count] != 0)
            allTipArr = [allTipArr arrayByAddingObjectsFromArray:[dealThingsDic objectForKey:@"commOpinion"]];
        if([[dealThingsDic objectForKey:@"userOpinion"] count] != 0)
            allTipArr = [allTipArr arrayByAddingObjectsFromArray:[dealThingsDic objectForKey:@"userOpinion"]];
    }
    
    [self initView];
    
    if([[dealThingsDic objectForKey:@"receiverName"] count] != 0)
    {
        toUserIdStr = [[[dealThingsDic objectForKey:@"receiverName"] objectAtIndex:0] objectForKey:@"value"];
        toUserNameStr = [[[dealThingsDic objectForKey:@"receiverName"] objectAtIndex:0] objectForKey:@"text"];
    }
    
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismisskeyBoard)];
    [dealThingsScr addGestureRecognizer:tap];
}

- (void)initView
{
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 100, 20)];
    titleLabel.text = @"文件标题：";
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.font = HEIGHT_FONT(16.0f);
    [dealThingsScr addSubview:titleLabel];
    
    UILabel *titleLabel2 = [[UILabel alloc] initWithFrame:CGRectMake(10, 35, 300, 20)];
    titleLabel2.text = titleStr;
    titleLabel2.font = HEIGHT_FONT(15.0f);
    titleLabel2.backgroundColor = [UIColor clearColor];
    titleLabel2.textColor = NOTICE_CONTENT_BACKCOLOR;
    [dealThingsScr addSubview:titleLabel2];
    
    CGSize size;
    if(titleStr.length != 0)
    {
        size=[HWLabelTextSize getSuitSizeWithString:titleStr fontSize:15 bold:YES sizeOfX:300];
        if(size.height<=16.702000)
            size= CGSizeMake(210, 20);
        else
            size= CGSizeMake(210, size.height/16.702000*20);
    }
    titleLabel2.frame = CGRectMake(10, 35, 300, size.height);
    
    int offY;
    if(size.height > 40)
    {
        titleLabel2.numberOfLines = 2;//(int)(size.height-20)/20;
        offY = size.height -20;
    }
    
    UILabel *tipLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 60+offY, 100, 20)];
    tipLabel.text = @"签署意见：";
    tipLabel.backgroundColor = [UIColor clearColor];
    tipLabel.font = HEIGHT_FONT(16.0f);
    [dealThingsScr addSubview:tipLabel];
    
    UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(10, 85+offY, 300, 200)];
    image.image = [UIImage imageNamed:@"textarea_hover.png"];
    image.userInteractionEnabled= YES;
    [dealThingsScr addSubview:image];
    
    tipTextView = [[UITextView alloc] initWithFrame:CGRectMake(0, 0, 300, 170)];
//    tipTextView.editable = NO;
    tipTextView.delegate =self;
    [image addSubview:tipTextView];
    
    UILabel *tipStyle = [[UILabel alloc] initWithFrame:CGRectMake(5, 170, 100, 30)];
    tipStyle.textColor = [UIColor grayColor];
    tipStyle.text = @"意见模板";
    tipStyle.font = NORMAL_FONT(14.0f);
    [image addSubview:tipStyle];
    
    UIButton *selectTip = [UIButton buttonWithType:UIButtonTypeCustom];
    selectTip.frame = CGRectMake(270, 170, 30, 30);
    [selectTip addTarget:self action:@selector(slectTipAction) forControlEvents:UIControlEventTouchUpInside];
    [selectTip setBackgroundImage:[UIImage imageNamed:@"scetel.png"] forState:UIControlStateNormal];
    [image addSubview:selectTip];
    
    
    UILabel *nextStepLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 295+offY, 300, 20)];
    nextStepLabel.text = [NSString stringWithFormat:@"下一步处理步骤：%@",[[[dealThingsDic objectForKey:@"nextTransition"] objectAtIndex:0]objectForKey:@"text"]];
    nextStepLabel.backgroundColor = [UIColor clearColor];
    nextStepLabel.font = HEIGHT_FONT(15.0f);
    [dealThingsScr addSubview:nextStepLabel];
    
    
    UILabel *nextStepPeopleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 320+offY, 150, 20)];
    nextStepPeopleLabel.text = @"选择下一步处理人：";
    nextStepPeopleLabel.backgroundColor = [UIColor clearColor];
    nextStepPeopleLabel.font = HEIGHT_FONT(15.0f);
    [dealThingsScr addSubview:nextStepPeopleLabel];
    
    UIButton *addPeopleButton = [UIButton buttonWithType:UIButtonTypeCustom];
    addPeopleButton.frame = CGRectMake(150, 320+offY, 20, 20);
    [addPeopleButton addTarget:self action:@selector(addPeopleAction) forControlEvents:UIControlEventTouchUpInside];
    [addPeopleButton setBackgroundImage:[UIImage imageNamed:@"send_add.png"] forState:UIControlStateNormal];
    [dealThingsScr addSubview:addPeopleButton];
    
    dealPeopleTextView = [[UITextView alloc] initWithFrame:CGRectMake(10, 345+offY, 300, 100)];
    dealPeopleTextView.editable = NO;
    if([[dealThingsDic objectForKey:@"receiverName"] count] != 0)
        dealPeopleTextView.text = [[[dealThingsDic objectForKey:@"receiverName"] objectAtIndex:0] objectForKey:@"text"];
    else
        dealPeopleTextView.text = @"";
    [dealThingsScr addSubview:dealPeopleTextView];
    
    UIButton *submitButton = [UIButton buttonWithType:UIButtonTypeCustom];
    submitButton.frame = CGRectMake(120, 455+offY, 80, 30);
    [submitButton setTitle:@"确 定" forState:UIControlStateNormal];
    [submitButton addTarget:self action:@selector(submitAction) forControlEvents:UIControlEventTouchUpInside];
    [submitButton setBackgroundImage:[UIImage imageNamed:@"but.png"] forState:UIControlStateNormal];
    [submitButton setBackgroundImage:[UIImage imageNamed:@"but_hover.png"] forState:UIControlStateNormal];
    [dealThingsScr addSubview:submitButton];
    
    dealThingsScr.contentSize = CGSizeMake(320, 500+offY);
}

- (void)slectTipAction
{
    //选择意见
    if(selectTipBackView)
        [selectTipBackView removeFromSuperview];
    
    if(!allTipArr)
    {
        allTipArr = [[NSArray alloc] init];
        if([[dealThingsDic objectForKey:@"commOpinion"] count] != 0)
            allTipArr = [allTipArr arrayByAddingObjectsFromArray:[dealThingsDic objectForKey:@"commOpinion"]];
        if([[dealThingsDic objectForKey:@"userOpinion"] count] != 0)
            allTipArr = [allTipArr arrayByAddingObjectsFromArray:[dealThingsDic objectForKey:@"userOpinion"]];
    }
    
    
    selectTipBackView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, self.view.frame.size.height)];
    selectTipBackView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:selectTipBackView];
    
    
    UIImageView *backImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, self.view.frame.size.height)];
    backImage.alpha = 0.5;
    backImage.backgroundColor = [UIColor blackColor];
    [selectTipBackView addSubview:backImage];
    
    
    UIView *contentView = [[UIView alloc] initWithFrame:CGRectMake(10, 80, 300, self.view.frame.size.height-160)];
    [selectTipBackView addSubview:contentView];
    
    UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 300, 30)];
    title.text = @"请选择签收意见";
    title.backgroundColor = [UIColor blackColor];
    title.textColor = [UIColor whiteColor];
    title.font = HEIGHT_FONT(16.0f);
    [contentView addSubview:title];
    
    table = [[UITableView alloc] initWithFrame:CGRectMake(0, 30, 300, self.view.frame.size.height-160-75) style:UITableViewStylePlain];
    table.delegate = self;
    table.dataSource = self;
//    table.separatorStyle = UITableViewCellSelectionStyleNone;
    [contentView addSubview:table];
    
    
    UIView *buttonBack = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height-160-75+30, 300, 45)];
    buttonBack.backgroundColor = NOTICEBOARD_LINE_COLOR;
    [contentView addSubview:buttonBack];
    
    UIButton *sureButton = [UIButton buttonWithType:UIButtonTypeCustom];
    sureButton.frame = CGRectMake(10, 5, 130, 30);
    sureButton.tag = 0;
    [sureButton setBackgroundColor:NOTICEBOARD_BACKCOLOR];
    [sureButton setTitle:@"确定" forState:UIControlStateNormal];
    [sureButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [sureButton addTarget:self action:@selector(selectTip:) forControlEvents:UIControlEventTouchUpInside];
    [buttonBack addSubview:sureButton];
    
    UIButton *cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
    cancelButton.frame = CGRectMake(160, 5, 130, 30);
    cancelButton.tag = 1;
    [cancelButton setBackgroundColor:NOTICEBOARD_BACKCOLOR];
    [cancelButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [cancelButton setTitle:@"取消" forState:UIControlStateNormal];
    [cancelButton addTarget:self action:@selector(selectTip:) forControlEvents:UIControlEventTouchUpInside];
    [buttonBack addSubview:cancelButton];
}

- (void)selectTip:(UIButton *)button
{
    if(tipLabelshow)
        [tipTextView removeFromSuperview];
    
    tipLabelshow = [[UILabel alloc] init];
    tipLabelshow.font = HEIGHT_FONT(10);
    tipLabelshow.numberOfLines = selectTipArr.count;
    tipLabelshow.frame = CGRectMake(20, 30, 100, selectTipArr.count*20);

    if(button.tag == 0)
    {
        NSMutableString *tempStr = [[NSMutableString alloc] init];
        NSMutableString *tempStr2 = [[NSMutableString alloc] init];
        for (int i = 0; i < [selectTipArr count]; i++)
        {
            NSString *tempIdStr = [selectTipArr objectAtIndex:i];
            tempStr.length == 0?[tempStr appendString:@""]:[tempStr appendString:@"\n"];
            [tempStr appendString:tempIdStr];
            
            tempStr2.length == 0?[tempStr2 appendString:@""]:[tempStr2 appendString:@"\n"];
            [tempStr2 appendString:tempIdStr];
        }
//        tipTextView.text = tempStr;
        tipSelectStr = tempStr2;
        tipLabelshow.text = tempStr;
    }
    [tipTextView addSubview:tipLabelshow];
    
    if(selectTipBackView)
        [selectTipBackView removeFromSuperview];
}

- (void)submitAction
{
    if(tipTextView.text.length == 0 && tipLabelshow.text.length ==0)
        [[NSNotificationCenter defaultCenter] postNotificationName:@"TIP" object:@{@"msg":@"请填写签署内容"}];
    else if(toUserNameStr.length == 0)
        [[NSNotificationCenter defaultCenter] postNotificationName:@"TIP" object:@{@"msg":@"没有选择后继步骤处理人"}];
    else
    {
        //确认
        [[NSNotificationCenter defaultCenter] postNotificationName:@"LOAD" object:nil];
        
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            
            NSString *param3 = toUserIdStr.length==0?@"":toUserIdStr;
            NSString *param4 = toUserNameStr.length == 0?@"":toUserNameStr;
            NSString *param7 = [[[dealThingsDic objectForKey:@"nextTransition"] objectAtIndex:0] objectForKey:@"value"];
            
            
            NSString *param5 = [tipTextView.text stringByReplacingOccurrencesOfString:@"\n" withString:@"|"];
            NSMutableString *param6 = [[NSMutableString alloc] init];
            for (int i = 0; i < [allTipArr count]; i++)
            {
                NSString *tempIdStr = [allTipArr objectAtIndex:i];
                param6.length == 0?[param6 appendString:@""]:[param6 appendString:@"|"];
                [param6 appendString:tempIdStr];
            }
            
            NSString *temp = [tipSelectStr stringByReplacingOccurrencesOfString:@"\n" withString:@"|"];
            NSString *param8 = [NSString stringWithFormat:@"%@ %@",tipTextView.text,temp];

    //        transitionGuidStr = [[[dealThingsDic objectForKey:@"nextTransition"] objectAtIndex:0]objectForKey:@"value"];
            NSLog(@"workItemGuidStr--%@",workItemGuidStr);
            NSLog(@"operationGuidStr---%@",operationGuidStr);
            NSLog(@"transitionGuidStr--%@",transitionGuidStr);
            NSLog(@"param3--%@",param3);
            NSLog(@"param4--%@",param4);
            NSLog(@"param5---%@",param5);
            NSLog(@"param8---%@",param8);
            NSLog(@"param7---%@",param7);
            
            NSDictionary *dic = [[SendHttpOperation shareSendHttpOperation] CommonOperationHandlePass_SingleTransition:TEMP_USERNAME
                                                                                                          WorkItemGuid:workItemGuidStr
                                                                                                         OperationGuid:operationGuidStr
                                                                                                        TransitionGuid:transitionGuidStr
                                                                                                          userGuidList:param3
                                                                                                          userNameList:param4
                                                                                                               opinion:param8
                                                                                                                 toSel:param5
                                                                                                        nextTransition:param7];
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [[NSNotificationCenter defaultCenter] postNotificationName:@"REMOVE" object:nil];
                if ([[dic objectForKey:@"errcode"] isEqualToString:@"0"])
                {
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"TIP" object:@{@"msg":@"处理成功"}];
                    NSArray *array = [self.navigationController viewControllers];
                    [self.navigationController popToViewController:array[3] animated:YES];
                }
                else
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"TIP" object:@{@"msg":([[dic objectForKey:@"errcode"]intValue]==1?@"处理失败":@"用户身份验证失败")}];
            });
        });
    }
}

//添加收件人
- (void)addPeopleAction
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"LOAD" object:nil];
    [[SendHttpOperation shareSendHttpOperation] GetUserList:@"GetUserList.ashx"];
    [SendHttpOperation shareSendHttpOperation].getUserListDelegate = self;
}

//获取收件人回掉函数并且进入选择收件人界面
- (void)passGetUserList:(NSDictionary *)getUserListDic
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"REMOVE" object:nil];
    
    if(!tempSelectArr)
        tempSelectArr = [[NSMutableArray alloc] init];
    
    if([[dealThingsDic objectForKey:@"receiverName"]count] !=0)
    {
        tempSelectArr = [NSArray arrayWithObject:[[[dealThingsDic objectForKey:@"receiverName"] objectAtIndex:0] objectForKey:@"value"]];
    }
    
    SelectReceiverList *instance = [[SelectReceiverList alloc] init];
    instance.flag = 0;
    instance.selectListArr = [NSMutableArray arrayWithArray:(tempSelectArr.count ==0?@[]:tempSelectArr)];
    instance.allReceiverListArr = [NSMutableArray arrayWithArray:[[[getUserListDic objectForKey:@"result"] objectForKey:@"list"] objectForKey:@"data"]];
    instance.delegate = self;
    [self.navigationController pushViewController:instance animated:YES];
}

//回传已经选择的收件人
//将收件人数据保存并且拼装成参数格式待使用
- (void)passList:(NSArray *)listArr
{
    if(!tempSelectArr)
        tempSelectArr = [[NSArray alloc] initWithArray:listArr];
    
    NSMutableString *tempStr1 = [[NSMutableString alloc] init];
    NSMutableString *tempStr2 = [[NSMutableString alloc] init];
    for (int i = 0; i < [listArr count]; i++)
    {
        NSString *tempIdStr = [[listArr objectAtIndex:i] objectAtIndex:0];
        tempStr1.length == 0?[tempStr1 appendString:@""]:[tempStr1 appendString:@";"];
        [tempStr1 appendString:tempIdStr];
        
        NSString *tempNameStr = [[listArr objectAtIndex:i] objectAtIndex:4];
        tempStr2.length == 0?[tempStr2 appendString:@""]:[tempStr2 appendString:@";"];
        [tempStr2 appendString:tempNameStr];
    }
    
    toUserIdStr = [NSString stringWithFormat:@"%@;",tempStr1];
    toUserNameStr = [NSString stringWithFormat:@"%@;",tempStr2];
    NSLog(@"toUserNameStr-->%@",toUserNameStr);
    
    dealPeopleTextView.text = [NSString stringWithFormat:@"%@",toUserNameStr];
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if(range.length != 1 &&[text isEqualToString:@"\n"])
    {
        [self dismisskeyBoard];
        return NO;
    }
    else
        return YES;
}

#pragma mark UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 45;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return allTipArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    
    NSArray *subviews = [[NSArray alloc] initWithArray:cell.contentView.subviews];
    for (UIView *subview in subviews)
    {
        [subview removeFromSuperview];
    }
    
    //自定义分割线
//    UIImageView *line = [[UIImageView alloc] initWithFrame:CGRectMake(0, 45, 320, 1)];
//    line.backgroundColor = NOTICE_CONTENT_BACKCOLOR;
//    [cell.contentView addSubview:line];
    
    UILabel *tipLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 150, 25)];
    tipLabel.text = [allTipArr objectAtIndex:indexPath.row];
    tipLabel.font = HEIGHT_FONT(15.0f);
    [cell.contentView addSubview:tipLabel];
    
    
    UIImageView *slectImage = [[UIImageView alloc] initWithFrame:CGRectMake(273, 14, 17, 17)];
    [cell.contentView addSubview:slectImage];
    
    if([selectTipArr containsObject:[allTipArr objectAtIndex:indexPath.row]])
        slectImage.image = [UIImage imageNamed:@"contact_checkbox_c.png"];
    else
        slectImage.image = [UIImage imageNamed:@"contact_checkbox_n.png"];
    
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(!selectTipArr)
        selectTipArr = [[NSMutableArray alloc] init];
    
    if([selectTipArr containsObject:[allTipArr objectAtIndex:indexPath.row]])
        [selectTipArr removeObject:[allTipArr objectAtIndex:indexPath.row]];
    else
        [selectTipArr addObject:[allTipArr objectAtIndex:indexPath.row]];
    
    [table reloadData];
    
}



- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
